﻿namespace ReadeWriteLock
{
    internal class Program
    {
        public static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();
        public static int count = 0;
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");

            Task.Run(() =>
            {
                while (true)
                {
                    Read();
                }
            });

            Task.Run(() =>
            {
                while (true)
                {
                    Write();
                }
            });

            Console.ReadLine();
        }


        private static void Read()
        {
            rwLock.EnterReadLock();

            try
            {
                // 读取数据
                Console.WriteLine($"[读] {Thread.CurrentThread.ManagedThreadId} 读取到 {count}");
                Thread.Sleep(10); // 模拟耗时
            }
            finally
            {
                rwLock.ExitReadLock();
            }
        }

        private static void Write()
        {
            rwLock.EnterWriteLock();
            try
            {
                // 写入数据
                count++;
                Console.WriteLine($"[写] {Thread.CurrentThread.ManagedThreadId} 写入了 {count}");
                Thread.Sleep(100); // 模拟耗时
            }
            finally
            {
                rwLock.ExitWriteLock();
            }
        }
    }

}
